<template>
    <div class="layout">
        <div class="login_left">
            <div class="bg_text">
                <span>Copyright&copy;2021- 2022 keyid.cn. 版权所有</span>
                <span>增值电信业务经营许可证： 沪B2-20211704 | 沪ICP备2021020699号-2</span>
            </div>
            <div class="banner"></div>
        </div>

        <div class="login_right">
            <div class="login_top">
                <div class="login_top_img">
                    <img src="@/assets/login/login_log.png" alt="" />
                </div>
                <p class="login_top_border"></p>
                <p class="login_top_text">用客易达连接客户</p>
            </div>

            <div class="login_container">
                <el-tabs v-model="activeName" @tab-change="handleClick">
                    <el-tab-pane label="账号登录" name="first">
                        <el-form
                            ref="ruleForm"
                            :model="numberValidateForm"
                            class="demo-ruleForm"
                            :rules="rules"
                            size="large">
                            <el-form-item prop="phone">
                                <el-input
                                    v-model.number="numberValidateForm.phone"
                                    type="text"
                                    placeholder="手机号"
                                    autocomplete="off"
                                    maxlength="11"></el-input>
                            </el-form-item>
                            <el-form-item v-if="visible" prop="password">
                                <el-input
                                    v-model="numberValidateForm.password"
                                    type="password"
                                    placeholder="请输入密码"
                                    minlength="6"
                                    maxlength="20">
                                </el-input>
                            </el-form-item>
                            <el-form-item v-else prop="phone">
                                <el-input
                                    v-model="numberValidateForm.password"
                                    type="text"
                                    placeholder="请输入密码"
                                    minlength="6"
                                    maxlength="20">
                                    <template #suffix>
                                        <div class="isvisible">
                                            <img src="@/assets/login/invisible.png" alt="" />
                                        </div>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <div class="remember">
                                <div class="remember_password">
                                    <el-checkbox v-model="record">记住密码</el-checkbox>
                                </div>
                                <span class="forget_password" @click="goForget">忘记密码</span>
                            </div>
                            <div class="agreement">
                                登录即表明同意<span @click="handleAgreement('userAgreement')">《平台协议》</span> 和
                                <span @click="handleAgreement('privacyAgreement')">《隐私声明》</span>
                            </div>
                            <el-button type="primary" @click="submitForm(ruleForm)">登录</el-button>
                            <p class="register-tip-text">
                                还没有账号？<span class="text" @click="goRegister">去注册</span>
                            </p>
                        </el-form>
                    </el-tab-pane>

                    <el-tab-pane label="验证码登录" name="second">
                        <el-form
                            ref="ruleFormRef"
                            :model="numberValidateForm"
                            class="demo-ruleForm"
                            :rules="rules"
                            size="large">
                            <el-form-item prop="phone">
                                <el-input
                                    v-model.number="numberValidateForm.phone"
                                    type="text"
                                    placeholder="手机号"
                                    autocomplete="off"
                                    max-length="11"></el-input>
                            </el-form-item>

                            <el-form-item prop="imgCode">
                                <el-input
                                    v-model="numberValidateForm.imgCode"
                                    type="text"
                                    placeholder="请填写图片验证码"
                                    maxlength="4">
                                    <template #suffix>
                                        <div class="imgCode" @click="randomCode">
                                            <img :src="getImgCode" alt="" />
                                        </div>
                                    </template>
                                </el-input>
                            </el-form-item>

                            <el-form-item prop="verificationCode">
                                <el-input
                                    v-model="numberValidateForm.verificationCode"
                                    type="text"
                                    placeholder="验证码"
                                    max-length="6">
                                    <template #suffix>
                                        <div v-show="sendAuthCode" class="getCode" @click="getPhoneCode(ruleFormRef)">
                                            获取验证码
                                        </div>
                                        <div v-show="!sendAuthCode" class="getCode countDown">
                                            {{ autoTime }}后重新获取
                                        </div>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <div class="agreement">
                                登录即表明同意<span @click="handleAgreement('userAgreement')">《平台协议》</span> 和
                                <span @click="handleAgreement('privacyAgreement')">《隐私声明》</span>
                            </div>
                            <el-button type="primary" @click="registerCode(ruleFormRef)">登录</el-button>
                            <p class="register-tip-text">
                                还没有账号？<span class="text" @click="goRegister">去注册</span>
                            </p>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
                <div class="other">
                    <div class="other_title">
                        <p class="other_title_border"></p>
                        <p class="other_title_text">其他方式</p>
                        <p class="other_title_border"></p>
                    </div>
                    <div class="other_img" @click="goAuth">
                        <img src="@/assets/login/login_qw.png" alt="企业微信登录" />
                    </div>
                </div>
            </div>
        </div>
    </div>
    <el-dialog v-model="isShowServiceCode" width="680px" center @close="onClose">
        <div class="service_code">
            <h4>申请试用</h4>
            <p>非常感谢您对平台的关注，申请试用请联系客服，谢谢！</p>
            <img src="https://static.scrm.keyid.cn/assets/images/global/service.png" alt="" />
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed, onUnmounted } from 'vue';
import { ElForm, ElMessage } from 'element-plus';
import { useStore } from '@/store';
import { useRoute } from 'vue-router';
import router from '@/router';
import { login, qrcodeLink, verificationCodeLogin, noteCode, getauthCode } from '@/api/login';
import { validatorPassword, validatePhone, validateCode, validatorNote } from '@/utils/validate';
import { getImageCode } from '@/api/common';
import domain from '@/utils/domain';
import { IsNotEmpty } from '@/utils/utils';
import storage from '@/utils/storage';

const ruleForm = ref<InstanceType<typeof ElForm>>();
const ruleFormRef = ref<InstanceType<typeof ElForm>>();

const store = useStore();
const route = useRoute();
const activeName = ref('first');
const visible = ref(true);
const autoTime = ref(0);
const sendAuthCode = ref(true);
const getImgCode = ref(`${domain.BASE_API_URL}/scrm-api/console/register/captcha-show?captcha_type=sms_login`);
const record = ref(true);

const handleClick = (tab: string, event: Event) => {
    randomCode();
};
const numberValidateForm = reactive({
    // phone: storage.has('_user') ? storage.get('_user').phone : '15152970328',
    // password: storage.has('_user') ? storage.get('_user').password : 'zw123456',
    phone: storage.has('_user') ? storage.get('_user').phone : '',
    password: storage.has('_user') ? storage.get('_user').password : '',
    imgCode: '',
    verificationCode: ''
});
/**
 * 校验请求参数中是否写到 auth_code 发起企微登录请求
 */
const wxLoginSend = (val?: string) => {
    const params = {
        auth_code: val
    };
    getauthCode(params)
        .then((data: any) => {
            store.dispatch('user/login', data);
            router.push({ path: '/home' });
            // if (data.account_list) {
            //   store.dispatch('user/loginMultiAccount', data)
            //   router.push({ path: '/selectFirm' })
            // } else {
            //   store.dispatch('user/login', data)
            //   router.push({ path: '/home' })
            // }
            ElMessage.success('登录成功');
        })
        .catch((e: any) => {
            ElMessage.error('扫码登录失败，请联系企业管理员！');
        });
};
// 手机验证
const phone = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('手机号不能为空！'));
    else if (validatePhone(value)) {
        callback(new Error('手机格式有误！'));
    } else {
        callback();
    }
};
// 图片验证
const auth = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('验证码不能为空！'));
    else if (validateCode(value)) {
        callback(new Error('验证码格式错误！'));
    } else {
        callback();
    }
};
// 密码验证
const password = (rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('密码不能为空！'));
    } else if (validatorPassword(value)) {
        callback(new Error('密码为6~20位字母+数字组合'));
    } else callback();
};
// 短信验证
const note = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('验证码不能为空！'));
    else if (validatorNote(value)) {
        callback(new Error('验证码格式错误！'));
    } else {
        callback();
    }
};
const rules = reactive({
    phone: [{ validator: phone, trigger: 'change' }],
    imgCode: [{ validator: auth, trigger: 'change' }],
    password: [{ validator: password, trigger: 'change' }],
    verificationCode: [{ validator: note, trigger: 'change' }]
});

//登录
const submitForm = (formEl: any) => {
    if (!formEl) return;
    // 添加客户/线索，记住下次不再选择
    localStorage.removeItem('customerType');
    localStorage.removeItem('clueType');
    store.commit('user/clearUser');
    store.commit('menu/clearMenu');
    sessionStorage.clear();
    localStorage.clear();
    formEl.validate((valid: any) => {
        if (valid) {
            if (numberValidateForm.phone != '' && numberValidateForm.password != '') {
                const { phone, password } = numberValidateForm;
                const params = {
                    mobile: phone + '',
                    password
                };
                login(params).then((data: any) => {
                    // 清空登录状态
                    if (IsNotEmpty(data?.account_list)) {
                        store.dispatch('user/loginMultiAccount', data);
                        router.push({ path: '/selectFirm' });
                    } else {
                        store.dispatch('user/login', data);
                        router.push({ path: '/home' });
                    }
                    ElMessage.success('登录成功');
                });
            } else {
                ElMessage.error('请输入账号或密码');
            }
        } else {
            return false;
        }
    });
};

// 验证码登录
const registerCode = (formEl: any) => {
    if (!formEl) return;
    // 添加客户/线索，记住下次不再选择
    localStorage.removeItem('customerType');
    localStorage.removeItem('clueType');
    formEl.validate((valid: any) => {
        if (valid) {
            const { phone, verificationCode } = numberValidateForm;
            const params = {
                mobile: phone + '',
                sms_code: verificationCode
            };
            storage.remove('power-code');
            storage.remove('zw-scrm-state');
            storage.remove('add_customer_select');
            storage.remove('add_customer_optional');
            store.commit('user/clearUser');
            store.commit('menu/clearMenu');
            sessionStorage.clear();
            localStorage.clear();
            verificationCodeLogin(params).then((data: any) => {
                // 清空登录状态
                if (data.account_list) {
                    store.dispatch('user/loginMultiAccount', data);
                    router.push({ path: '/selectFirm' });
                } else {
                    store.dispatch('user/login', data);
                    router.push({ path: '/home' });
                }
                ElMessage.success('登录成功');
            });
        } else {
            return false;
        }
    });
};

const randomCode = async () => {
    const res: any = await getImageCode({ captcha_type: 'sms_login' });
    getImgCode.value = `data:image/png;base64,${res.base64_image}`;
};
const getPhoneCode = (formEl: any) => {
    if (numberValidateForm.phone != '' && numberValidateForm.imgCode != '') {
        const { phone, imgCode, verificationCode } = numberValidateForm;
        const params = {
            mobile: phone + '',
            image_verify_code: imgCode,
            sms_type: 'sms_login'
        };
        noteCode(params)
            .then((data: any) => {
                sendAuthCode.value = false;
                autoTime.value = 60;
                const autoTimeTimer = setInterval(() => {
                    autoTime.value--;
                    if (autoTime.value <= 0) {
                        sendAuthCode.value = true;
                        clearInterval(autoTimeTimer);
                    }
                }, 1000);
            })
            .catch((err: any) => {
                if (err.code == 10001) {
                    ElMessage.error(err.msg);
                    randomCode();
                }
            });
    } else {
        ElMessage.error('请填写手机号或图片验证码');
    }
};
const handleAgreement = (show: any) => {
    window.open(`/agreement?show=${show}`);
};
const goRegister = () => {
    router.push({ path: '/register' });
};
const goAuth = () => {
    const param = {
        redirect_uri: `${domain.SITE_URL}/login`
    };
    qrcodeLink(param).then((data: any) => {
        window.location.href = data.link;
    });
};
// 忘记密码
const goForget = () => {
    router.push({ path: '/forget', query: { phone: numberValidateForm.phone } });
};
// 修改记住密码多选框样式

watch(
    () => record.value,
    val => {
        if (val) {
            storage.set('_user', numberValidateForm, 7 * 24 * 3600);
        }
    }
);
onMounted(() => {
    onClose();
    const wxAuthCode = route.query?.auth_code;
    if (wxAuthCode) {
        wxLoginSend(wxAuthCode);
    }
});
const forgetPassword = () => {
    router.push({ path: '/forget' });
};

const isShowServiceCode = computed(() => {
    return store.getters['user/getAccountStatus'] === 406;
});
const onClose = () => {
    store.commit('user/setAccountStatus', null);
};
</script>

<style lang="scss" scoped>
.layout {
    display: flex;
    height: 100%;
    width: 100%;

    .login_left {
        width: 58.34%;
        height: 100%;
        text-align: center;
        background: url('@/assets/login/login_bg_block.png') repeat center center;
        background-size: contain;
        position: relative;

        .bg_text {
            position: absolute;
            bottom: 4%;
            left: 50%;
            transform: translateX(-50%);
            width: 449px;
            color: #969696;
            font-size: 14px;

            // margin: 984px auto 0;
            span {
                display: block;
                margin: 3px 0;
            }
        }

        .banner {
            width: 64%;
            height: 61.11%;
            background: url('@/assets/login/login_bg_banner.png') no-repeat center center;
            background-size: contain;
            position: absolute;
            top: 27%;
            left: 50%;
            transform: translateX(-50%) translateY(-18%);
        }
    }

    .login_right {
        width: 41.66%;
        position: relative;
        background-color: #fff;

        .login_top {
            height: 23px;
            display: flex;
            align-items: center;
            margin: 21px 0 0 40px;

            &_img {
                width: 95px;
                height: 23px;

                img {
                    width: 100%;
                    height: 100%;
                }
            }

            &_border {
                height: 20px;
                margin: 0 14px;
                border-left: 1px solid #d0d0d0;
            }

            &_text {
                font-size: 14px;
                line-height: 14px;
                color: #33302d;
            }
        }
    }

    .login_container {
        width: 450px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translateX(-50%) translateY(-50%);

        :deep(.el-tabs) {
            .el-tabs__header {
                margin-bottom: 30px;

                .el-tabs__nav {
                    width: 100%;
                    text-align: center;

                    .el-tabs__item {
                        padding: 0 60px;
                    }
                }
            }
        }

        :deep(.el-input) {
            border-bottom: 1px solid #d9d9d9;

            .el-input__wrapper {
                padding: 0;
                box-shadow: none;
                box-sizing: border-box;
            }
        }

        .el-button {
            width: 100%;
        }

        .isvisible {
            width: 19px;
            height: 10px;
            cursor: pointer;

            img {
                width: 100%;
                height: 100%;
            }
        }

        .imgCode {
            width: 100px;
            height: 30px;
            margin-top: 4px;
            line-height: 30px;
            background: #f6f6f6;
            text-align: center;
            cursor: pointer;

            img {
                width: 100%;
                height: 100%;
            }
        }

        .getCode {
            color: #0081ff;
            height: 16px;
            font-size: 16px;
            line-height: 16px;
            cursor: pointer;
        }

        .countDown {
            color: #969696;
        }

        .remember {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            font-size: 14px;

            .remember_password {
                .check {
                    margin-right: 10px;
                }
            }

            .forget_password {
                color: #0081ff;
                cursor: pointer;
            }
        }

        .agreement {
            height: 14px;
            margin: 44px 0 16px;
            color: #696969;
            font-size: 14px;
            line-height: 14px;

            span {
                color: #0081ff;
                cursor: pointer;
            }
        }

        .register-tip-text {
            margin-top: 16px;
            font-size: 14px;
            color: #696969;

            .text {
                color: #0081ff;
                cursor: pointer;
            }
        }

        .other {
            &_title {
                display: flex;
                align-items: center;
                justify-content: space-between;
                height: 14px;
                line-height: 14px;
                font-size: 14px;
                color: #696969;
                margin-top: 60px;

                &_border {
                    width: 150px;
                    border-top: 1px solid #eaeaea;
                }
            }

            &_img {
                width: 36px;
                height: 30px;
                margin: 18px auto 0;

                img {
                    width: 100%;
                    height: 100%;
                }
            }
        }
    }
}

//@media (min-width: 2500px) {
//  .layout {
//    justify-content: center;
//  }
//}
.service_code {
    text-align: center;
    padding-bottom: 20px;
    color: #33302d;

    h4 {
        font-size: 24px;
        font-family: PingFangSC-Medium, 'PingFang SC';
    }

    p {
        margin: 26px 0;
    }

    img {
        width: 236px;
        height: 236px;
    }
}
</style>
